import 'dart:io';
import 'package:flutter/services.dart';
import 'package:path_provider/path_provider.dart';
import 'package:intl/intl.dart';
import '../models/index.dart';

/// 🎨 分享页面生成服务
/// 
/// 负责根据活动数据生成动态的HTML分享页面
class SharePageGeneratorService {
  static const String _templatePath = 'assets/share/activity_share.html';
  
  /// 生成活动分享页面
  /// 
  /// [activity] 活动数据
  /// [shareUrl] 分享链接
  /// 返回生成的HTML内容
  static Future<String> generateActivitySharePage({
    required ActivityModel activity,
    required String shareUrl,
  }) async {
    try {
      // 读取HTML模板
      final template = await rootBundle.loadString(_templatePath);
      
      // 准备替换数据
      final replacements = await _prepareReplacements(activity, shareUrl);
      
      // 执行内容替换
      String htmlContent = template;
      replacements.forEach((placeholder, value) {
        htmlContent = htmlContent.replaceAll(placeholder, value);
      });
      
      return htmlContent;
    } catch (e) {
      print('🚫 生成分享页面失败: $e');
      return _generateFallbackPage(activity, shareUrl);
    }
  }
  
  /// 准备替换数据
  static Future<Map<String, String>> _prepareReplacements(
    ActivityModel activity,
    String shareUrl,
  ) async {
    final now = DateTime.now();
    final timeFormatter = DateFormat('yyyy年MM月dd日 HH:mm');
    
    return {
      // 基础活动信息
      '{{ACTIVITY_ID}}': activity.id,
      '{{ACTIVITY_TITLE}}': _sanitizeHtml(activity.title),
      '{{ACTIVITY_DESCRIPTION}}': _sanitizeHtml(
        activity.description.isNotEmpty ? activity.description : '我在玩真的发现了一个有趣的活动，快来看看吧！'
      ),
      '{{ACTIVITY_IMAGE}}': _getActivityImage(activity),
      '{{ACTIVITY_TIME}}': _formatActivityTime(activity),
      '{{ACTIVITY_LOCATION}}': _sanitizeHtml(activity.location),
      
      // 分享相关
      '{{SHARE_URL}}': shareUrl,
      '{{SHARE_TIME}}': timeFormatter.format(now),
      
      // 微信相关（可选，需要微信公众号配置）
      '{{WECHAT_APP_ID}}': '', // 如果有微信公众号，在这里配置
      '{{WECHAT_TIMESTAMP}}': (now.millisecondsSinceEpoch ~/ 1000).toString(),
      '{{WECHAT_NONCE_STR}}': _generateNonceStr(),
      '{{WECHAT_SIGNATURE}}': '', // 需要后端生成
    };
  }
  
  /// 获取活动图片URL
  static String _getActivityImage(ActivityModel activity) {
    if (activity.imageUrl.isNotEmpty) {
      String imageUrl = activity.imageUrl;
      
      // 如果是相对路径，转换为绝对路径
      if (!imageUrl.startsWith('http')) {
        imageUrl = 'https://app.playtruly.cn$imageUrl';
      }
      
      return imageUrl;
    }
    
    // 使用默认图片
    return 'https://app.playtruly.cn/images/default/activity_placeholder.jpg';
  }
  
  /// 格式化活动时间
  static String _formatActivityTime(ActivityModel activity) {
    try {
      final formatter = DateFormat('MM月dd日 HH:mm');
      return formatter.format(activity.date);
    } catch (e) {
      print('🚫 格式化活动时间失败: $e');
    }
    
    return '待定';
  }
  
  /// HTML内容清理，防止XSS攻击
  static String _sanitizeHtml(String content) {
    return content
        .replaceAll('&', '&amp;')
        .replaceAll('<', '&lt;')
        .replaceAll('>', '&gt;')
        .replaceAll('"', '&quot;')
        .replaceAll("'", '&#x27;')
        .replaceAll('/', '&#x2F;');
  }
  
  /// 生成随机字符串
  static String _generateNonceStr() {
    const chars = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
    final random = DateTime.now().millisecondsSinceEpoch;
    final buffer = StringBuffer();
    
    for (int i = 0; i < 16; i++) {
      buffer.write(chars[(random + i) % chars.length]);
    }
    
    return buffer.toString();
  }
  
  /// 生成降级页面（当模板加载失败时）
  static String _generateFallbackPage(ActivityModel activity, String shareUrl) {
    final title = _sanitizeHtml(activity.title);
    final description = _sanitizeHtml(
      activity.description.isNotEmpty ? activity.description : '我在玩真的发现了一个有趣的活动，快来看看吧！'
    );
    
    return '''
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>$title - 玩真的</title>
    
    <!-- 微信分享优化 -->
    <meta property="og:title" content="$title">
    <meta property="og:description" content="$description">
    <meta property="og:url" content="$shareUrl">
    <meta property="og:type" content="website">
    
    <style>
        body {
            font-family: -apple-system, BlinkMacSystemFont, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            margin: 0;
            padding: 20px;
            min-height: 100vh;
            display: flex;
            align-items: center;
            justify-content: center;
        }
        .container {
            max-width: 400px;
            background: white;
            border-radius: 15px;
            padding: 30px;
            text-align: center;
            box-shadow: 0 10px 30px rgba(0,0,0,0.1);
        }
        .title {
            font-size: 24px;
            font-weight: bold;
            color: #333;
            margin-bottom: 15px;
        }
        .description {
            font-size: 16px;
            color: #666;
            margin-bottom: 30px;
            line-height: 1.5;
        }
        .download-btn {
            display: inline-block;
            background: #4CAF50;
            color: white;
            padding: 15px 30px;
            border-radius: 25px;
            text-decoration: none;
            font-weight: bold;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="title">$title</div>
        <div class="description">$description</div>
        <a href="#" class="download-btn" onclick="downloadApp()">下载玩真的APP</a>
    </div>
    
    <script>
        function downloadApp() {
            const userAgent = navigator.userAgent.toLowerCase();
            if (/android/i.test(userAgent)) {
                window.location.href = 'https://play.google.com/store/apps/details?id=com.playtruly.wanzhende2025';
            } else if (/iphone|ipad|ipod/i.test(userAgent)) {
                window.location.href = 'https://apps.apple.com/cn/app/id[YOUR_APP_ID]';
            } else {
                window.location.href = 'https://app.playtruly.cn/download';
            }
        }
    </script>
</body>
</html>
    ''';
  }
  
  /// 保存分享页面到本地文件（用于调试）
  static Future<String?> saveSharePageToFile({
    required String htmlContent,
    required String activityId,
  }) async {
    try {
      final directory = await getApplicationDocumentsDirectory();
      final file = File('${directory.path}/share_activity_$activityId.html');
      
      await file.writeAsString(htmlContent);
      
      print('📁 分享页面已保存到: ${file.path}');
      return file.path;
    } catch (e) {
      print('🚫 保存分享页面失败: $e');
      return null;
    }
  }
  
  /// 预览分享页面（用于开发调试）
  static Future<void> previewSharePage({
    required ActivityModel activity,
    required String shareUrl,
  }) async {
    try {
      final htmlContent = await generateActivitySharePage(
        activity: activity,
        shareUrl: shareUrl,
      );
      
      final filePath = await saveSharePageToFile(
        htmlContent: htmlContent,
        activityId: activity.id,
      );
      
      if (filePath != null) {
        print('🌐 预览链接: file://$filePath');
      }
    } catch (e) {
      print('🚫 预览分享页面失败: $e');
    }
  }
  
  /// 验证生成的HTML内容
  static bool validateHtmlContent(String htmlContent) {
    // 基础验证
    if (htmlContent.isEmpty) return false;
    if (!htmlContent.contains('<!DOCTYPE html>')) return false;
    if (!htmlContent.contains('<html')) return false;
    if (!htmlContent.contains('</html>')) return false;
    
    // 检查是否还有未替换的占位符
    if (htmlContent.contains('{{') && htmlContent.contains('}}')) {
      print('⚠️ 警告：HTML内容中仍有未替换的占位符');
      return false;
    }
    
    return true;
  }
  
  /// 生成分享页面的统计信息
  static Map<String, dynamic> generateSharePageStats({
    required ActivityModel activity,
    required String shareUrl,
  }) {
    return {
      'activityId': activity.id,
      'activityTitle': activity.title,
      'shareUrl': shareUrl,
      'generatedAt': DateTime.now().toIso8601String(),
      'hasImages': activity.imageUrl.isNotEmpty,
      'imageCount': 1,
      'hasStartTime': true,
    };
  }
}
